<script setup>
import { onMounted, ref } from 'vue';
import { getImageInfo } from '@/api/reportApi'; // 导入新创建的 API

import {
  ElButton,
  ElDatePicker,
  ElMessage,
  ElPagination,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import 'element-plus/dist/index.css';

// 定义响应式数据
const today = new Date().toISOString().split('T')[0]; // 获取今天的日期
const startDate = ref(today); // 设置开始日期为今天
const endDate = ref(today); // 设置结束日期为今天
const imageInfoData = ref([]); // 存储图像信息数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的条目数
const total = ref(0); // 总条目数

// 获取图像信息
const fetchImageInfo = async () => {
  const response = await getImageInfo(startDate.value, endDate.value, currentPage.value, pageSize.value);
  console.log('获取图像信息成功:', response.results);
  imageInfoData.value = response.results; // 更新图像信息数据
  total.value = response.total; // 更新总条目数
};

// 日期改变时的处理函数
function onDateChange() {
  if (endDate.value < startDate.value) {
    ElMessage.error('结束日期必须晚于开始日期');
    endDate.value = new Date(startDate.value);
  }
  console.log('日期已改变:', startDate.value, endDate.value);
}

// 快捷日期选择
function selectToday() {
  const today = new Date();
  startDate.value = today.toISOString().split('T')[0];
  endDate.value = today.toISOString().split('T')[0];
  fetchImageInfo(); // 自动查询今天的数据
}

function selectThisWeek() {
  const today = new Date();
  const firstDay = new Date(today.setDate(today.getDate() - today.getDay()));
  const lastDay = new Date(today.setDate(today.getDate() - today.getDay() + 6));
  startDate.value = firstDay.toISOString().split('T')[0];
  endDate.value = lastDay.toISOString().split('T')[0];
}

function selectThisMonth() {
  const today = new Date();
  const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
  const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
  startDate.value = firstDay.toISOString().split('T')[0];
  endDate.value = lastDay.toISOString().split('T')[0];
}

function selectLastQuarter() {
  const today = new Date();
  const currentQuarter = Math.floor((today.getMonth() + 3) / 3);
  const firstMonthOfQuarter = (currentQuarter - 2) * 3;
  const firstDay = new Date(today.getFullYear(), firstMonthOfQuarter, 1);
  const lastDay = new Date(today.getFullYear(), firstMonthOfQuarter + 3, 0);
  startDate.value = firstDay.toISOString().split('T')[0];
  endDate.value = lastDay.toISOString().split('T')[0];
}

function selectLastYear() {
  const today = new Date();
  const firstDay = new Date(today.getFullYear() - 1, 0, 1);
  const lastDay = new Date(today.getFullYear() - 1, 11, 31);
  startDate.value = firstDay.toISOString().split('T')[0];
  endDate.value = lastDay.toISOString().split('T')[0];
}

// 导出数据为 CSV
function exportData() {
  const csvContent = `data:text/csv;charset=utf-8,${imageInfoData.value
    .map((e) => Object.values(e).join(','))
    .join('\n')}`;
  const encodedUri = encodeURI(csvContent);
  const link = document.createElement('a');
  link.setAttribute('href', encodedUri);
  link.setAttribute('download', 'data.csv');
  document.body.append(link);
  link.click();
  link.remove();
}

// 日期格式化函数
const formatDate = (row) => {
  const date = new Date(row.entry_date);
  return date.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
};

onMounted(() => {
  fetchImageInfo();
});
</script>

<template>
  <div class="container mx-auto p-6">
    <!-- 标题 -->
    <h1 class="mb-6 text-3xl font-bold text-gray-800">分析报告</h1>

    <!-- 日期选择和快捷选项 -->
    <div class="mb-6 flex items-center space-x-4">
      <ElDatePicker
        v-model="startDate"
        type="date"
        placeholder="开始日期"
        format="YYYY-MM-DD"
        class="custom-datepicker"
        @change="onDateChange"
      />
      <span>到</span>
      <ElDatePicker
        v-model="endDate"
        type="date"
        placeholder="结束日期"
        format="YYYY-MM-DD"
        class="custom-datepicker"
        @change="onDateChange"
      />
      <div class="flex space-x-2">
        <ElButton @click="selectToday" type="primary">今日</ElButton>
        <ElButton @click="selectThisWeek" type="primary">本周</ElButton>
        <ElButton @click="selectThisMonth" type="primary">本月</ElButton>
        <ElButton @click="selectLastQuarter" type="primary">上季度</ElButton>
        <ElButton @click="selectLastYear" type="primary">上年度</ElButton>
        <ElButton @click="exportData" type="success">导出</ElButton>
        <ElButton @click="fetchImageInfo" type="info">查询</ElButton>
      </div>
    </div>

    <!-- 表格 -->
    <div class="mb-6 rounded-lg bg-white p-4 shadow-md">
      <ElTable :data="imageInfoData" style="width: 100%">
        <ElTableColumn prop="id" label="ID" />
        <ElTableColumn prop="image" label="图片" />
        <ElTableColumn prop="name" label="名称" />
        <ElTableColumn 
          :label="'录入日期'" 
          :formatter="formatDate" 
        />
        <ElTableColumn prop="recognition_result" label="识别结果" />
        <ElTableColumn prop="target_count" label="目标数目" />
        <ElTableColumn prop="duration" label="时长" />
        <ElTableColumn prop="save_path" label="保存路径" />
      </ElTable>

      <!-- 分页 -->
      <ElPagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="fetchImageInfo"
        class="mt-4"
      />
    </div>

    <!-- 分析报告 -->
    <div class="rounded-lg bg-white p-6 shadow-md">
      <h2 class="mb-4 text-xl font-semibold text-gray-700">分析报告详情</h2>
      <div class="flex h-32 items-center justify-center text-gray-600">
        这里是分析报告的详细内容。
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 自定义样式 */
.custom-datepicker {
  width: 200px;
  height: 40px; /* 调整高度 */
  line-height: 40px; /* 调整行高 */
}
</style>
